1

使用mocha测试含有es6 modules的代码是,需要使用babel-register来转化语法。babel-register跟项目中web端的项目共享同一份.babelrc。如下:

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": [
            "> 1%",
            "last 2 versions",
            "not ie <= 8"
          ]
        }
      }
    ],
    "stage-2"
  ],
  "plugins": [
    "transform-vue-jsx",
    "transform-runtime"
  ],
  "env": {
    "test" : {
      "presets": ["env", "stage-2"]
    }
  }
}

在windows powershell 中:

set BABEL_ENV=test | mocha --rquire babel-register 

这里要注意的是powershell中的管理命令连接符是 | ,而不是&&

在mocha的issue中,有一个是希望加入--env标志,但tj大神直接说不需要, 你干嘛不set xxx_env && mocha.

底下也有人给了另外的解决办法

Since this still seems to get a lot of traffic I thought I would throw out 
a relatively simply solution for people like me who wish there was a --env flag.
What I've been doing is add a test/mocha.env.js file in the repo, 
and then add --require test/mocha.env.js to mocha.opts:

// mocha.opts
--require babel-register
--require test/mocha.env.js
--timeout 60000

// mocha.env.js
process.env.NODE_ENV = 'test';



BBQ只有番薯
300 声望6 粉丝